/*
 * Module name : DiscountComponent
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import DiscountCollectionView from './DiscountCollectionView.js';

const template = require('./templates/DiscountComponent.mustache');

const DiscountComponent = Mn.View.extend({
    template: template,
    regions: {
        collection: {
            el: 'tbody.lines',
            replaceElement: true
        },
    },
    // Listen to child view events
    childViewEvents: {
        "up": "onUp",
        "down": "onDown",
        "edit": "onEdit",
        'delete': "onDelete",
        'destroy:modal': 'render',
        'cancel:form': 'render',
    },
    events: {
        'click .add-discount': 'onAdd'
    },
    initialize() {
        this.app = Radio.channel('priceStudyApp');
    },
    onRender() {
        if (this.collection.length > 0) {
            this.showChildView(
                'collection',
                new DiscountCollectionView({
                    collection: this.collection
                })
            );
        }
    },
    templateContext() {
        return {
            editable: this.getOption('editable'),
            hasItems: this.collection.length > 0
        };
    },
    onUp: function (model) {
        this.app.trigger('model:move:up', model);
    },
    onDown: function (model) {
        this.app.trigger('model:move:down', model);
    },
    onEdit(model) {
        let route = '/discounts/';
        this.app.trigger('navigate', route + model.get('id'));
    },
    onDelete(model) {
        this.app.trigger('discount:delete', model);
    },
    onAdd() {
        this.app.trigger('discount:add');
    }
});
export default DiscountComponent